package com.lleice.service.test;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.ConstVal;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.FileOutConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import cn.hutool.core.util.StrUtil;

/**
 * mybatis代码生成器
 * @author lizihao
 *
 */
public class MybatisGenerator {

	private final static String PARENT_PATH = "com.lleice.service";
	/**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (!StrUtil.isEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
    	try {
    		// 代码生成器
            AutoGenerator mpg = new AutoGenerator();

            // 全局配置
            GlobalConfig gc = new GlobalConfig();
            String projectPath = System.getProperty("user.dir");
            gc.setOutputDir(projectPath +"/src/main/resources");
            gc.setAuthor("lizihao");
            gc.setOpen(false);
            //实体属性 Swagger2 注解
            gc.setSwagger2(true); 
            mpg.setGlobalConfig(gc);

            // 数据源配置
            DataSourceConfig dsc = new DataSourceConfig();
            dsc.setUrl("jdbc:mysql://10.91.22.8:33066/chinaunicom_base_framework?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai");
            dsc.setDbType(DbType.MYSQL);
            dsc.setDriverName("com.mysql.cj.jdbc.Driver");
            dsc.setUsername("smartward");
            dsc.setPassword("i6OT5FF#Xot#T!53!kvR");
            mpg.setDataSource(dsc);

            // 包配置
            PackageConfig pc = new PackageConfig();
            pc.setModuleName(scanner("模块名(建议是table_prefix)"));
            mpg.setPackageInfo(pc);

            //配置模板
            TemplateConfig templateConfig = new TemplateConfig();

            templateConfig.setXml(null);
            mpg.setTemplate(templateConfig);

            // 策略配置
            StrategyConfig strategy = new StrategyConfig();
            strategy.setNaming(NamingStrategy.underline_to_camel);
            strategy.setColumnNaming(NamingStrategy.underline_to_camel);
            setSuperEntity(strategy,false);
            strategy.setEntityLombokModel(true);
            strategy.setRestControllerStyle(true);
            //写于父类中的公共字段
            strategy.setInclude(scanner("表名，多个英文逗号分割").split(","));
            strategy.setControllerMappingHyphenStyle(true);
            mpg.setStrategy(strategy);
            mpg.setTemplateEngine(new FreemarkerTemplateEngine());
            //自定义文件生成路径，包路径
            customPackagePath(pc,mpg,PARENT_PATH);
            
            mpg.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
        
    }
    /**
     * 不同的实体父类id
     * @param strategy 配置
     * @param isJustId 开关
     */
	private static void setSuperEntity(StrategyConfig strategy,boolean isJustId) {
		if(!isJustId) {
			//继承公用字段父类
			strategy.setSuperEntityClass("com.lleice.common.entity.base.CommonEntity");
			//子类不生成父类的字段
			strategy.setSuperEntityColumns("id","is_delete","is_enable","create_time","create_by","update_time","update_by");
		}else {
			strategy.setSuperEntityClass("com.lleice.common.entity.base.CommonIdEntity");
			strategy.setSuperEntityColumns("id");
		}
	}

    
    /**
     * 自定义包路径，文件生成路径，这边配置更灵活
     * 虽然也可以使用InjectionConfig设置FileOutConfig的方式设置路径
     * 这里直接使用Map方式注入ConfigBuilder配置对象更加直观
     * @param pc
     * @param mpg
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    public static void customPackagePath(PackageConfig pc,AutoGenerator mpg,String parentPath) throws NoSuchFieldException, IllegalAccessException {

        String projectPath = System.getProperty("user.dir");

        String moduleName = pc.getModuleName();

        /**
         * packageInfo配置controller、service、serviceImpl、entity、mapper等文件的包路径
         * 这里包路径可以根据实际情况灵活配置
         */
        Map<String,String> packageInfo = new HashMap<>(16);
        packageInfo.put(ConstVal.CONTROLLER, parentPath+"."+pc.getController()+"."+moduleName);
        packageInfo.put(ConstVal.SERVICE, parentPath+"."+pc.getService()+"."+moduleName);
        packageInfo.put(ConstVal.SERVICE_IMPL, parentPath+"."+pc.getService()+"."+moduleName+".impl");
        packageInfo.put(ConstVal.ENTITY, parentPath+"."+pc.getEntity()+"."+moduleName);
        packageInfo.put(ConstVal.MAPPER, parentPath+"."+pc.getMapper()+"."+moduleName);

        /**
         * pathInfo配置controller、service、serviceImpl、entity、mapper、mapper.xml等文件的生成路径
         * srcPath也可以更具实际情况灵活配置
         * 后面部分的路径是和上面packageInfo包路径对应的源码文件夹路径
         * 这里你可以选择注释其中某些路径，可忽略生成该类型的文件，例如:注释掉下面pathInfo中Controller的路径，就不会生成Controller文件
         */
        Map<String, String> pathInfo = new HashMap<String,String>(16);
        pathInfo.put(ConstVal.CONTROLLER_PATH, projectPath+"/src/main/resources/" + packageInfo.get(ConstVal.CONTROLLER).replaceAll("\\.", StringPool.BACK_SLASH + File.separator));
        pathInfo.put(ConstVal.SERVICE_PATH, projectPath+"/src/main/resources/" + packageInfo.get(ConstVal.SERVICE).replaceAll("\\.", StringPool.BACK_SLASH + File.separator));
        pathInfo.put(ConstVal.SERVICE_IMPL_PATH, projectPath+"/src/main/resources/" + packageInfo.get(ConstVal.SERVICE_IMPL).replaceAll("\\.", StringPool.BACK_SLASH + File.separator));
        pathInfo.put(ConstVal.ENTITY_PATH, projectPath+"/src/main/resources/" + packageInfo.get(ConstVal.ENTITY).replaceAll("\\.", StringPool.BACK_SLASH + File.separator));
        pathInfo.put(ConstVal.MAPPER_PATH, projectPath+"/src/main/resources/" + packageInfo.get(ConstVal.MAPPER).replaceAll("\\.", StringPool.BACK_SLASH + File.separator));
        pathInfo.put(ConstVal.XML_PATH, projectPath+"/src/main/resources/mapper/"+moduleName);
        pc.setPathInfo(pathInfo);

        /**
         * 创建configBuilder对象，传入必要的参数
         * 将以上的定义的包路径packageInfo配置到赋值到configBuilder对象的packageInfo属性上
         * 因为packageInfo是私有成员变量，也没有提交提供公共的方法，所以使用反射注入
         * 为啥要这么干，看源码去吧
         */
        ConfigBuilder configBuilder = new ConfigBuilder(mpg.getPackageInfo(), mpg.getDataSource(), mpg.getStrategy(), mpg.getTemplate(), mpg.getGlobalConfig());
        Field packageInfoField = configBuilder.getClass().getDeclaredField("packageInfo");
        packageInfoField.setAccessible(true);
        packageInfoField.set(configBuilder,packageInfo);

        /**
         * 设置配置对象
         */
        mpg.setConfig(configBuilder);
        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
            	Map<String, Object> map = new HashMap<String, Object>(16);
                //自定义配置，在模版中cfg.superColums 获取
                // TODO 这里解决子类会生成父类属性的问题，在模版里会用到该配置
                map.put("superColums", mpg.getConfig().getStrategyConfig().getSuperEntityColumns());
                this.setMap(map);
            }
        };
        String xmlTemplatePath = "/templates/mapper.xml.ftl";
        String mapperTemplatePath = "templates/mapper.java.ftl";
        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(xmlTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        focList.add(new FileOutConfig(mapperTemplatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
            	return projectPath+"/src/main/resources/" + packageInfo.get(ConstVal.MAPPER).replaceAll("\\.", StringPool.BACK_SLASH + File.separator);
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        //mpg.setCfg(cfg);
    }

}